<template>
  <div class="p-2">
    <div class="draggable-container">
      <div
        class="draggable-box"
        @mousedown="startDrag"
        @mousemove="onDrag"
        @mouseup="stopDrag"
        @click="toggleMenu"
        :style="{ top: position.y + 'px', left: position.x + 'px' }"
      >
        <img src="./fox.png" style="width: 95px; pointer-events: none" />
      </div>


      <transition name="fade">
        <div v-if="isMenuOpen" class="menu">
          <ul>
            <li>选项1</li>
            <li>选项2</li>
            <li>选项3</li>
          </ul>
        </div>
      </transition>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      position: { x: 1750, y: 900 },
      isDragging: false,
      isMenuOpen: false,
      initialX: 0,
      initialY: 0,
      wasDragging: false // 新增标志变量，用于记录是否处于拖动状态
    };
  },
  methods: {
    startDrag(e) {
      this.isDragging = true;
      this.initialX = e.clientX - this.position.x;
      this.initialY = e.clientY - this.position.y;
      // 添加全局事件监听器
      document.addEventListener('mousemove', this.onDrag);
      document.addEventListener('mouseup', this.stopDrag);
    },
    onDrag(e) {
      if (this.isDragging) {
        this.wasDragging = true; // 标记为正在拖动
        this.updatePosition(e.clientX, e.clientY);
      }
    },
    updatePosition(clientX, clientY) {
      const newX = clientX - this.initialX;
      const newY = clientY - this.initialY;

      // 使用 requestAnimationFrame 来平滑动画
      requestAnimationFrame(() => {
        this.position.x = newX;
        this.position.y = newY;
        this.isMenuOpen = false; // 位置变化时隐藏菜单
      });
    },
    stopDrag() {
      this.isDragging = false;
      // 移除全局事件监听器
      document.removeEventListener('mousemove', this.onDrag);
      document.removeEventListener('mouseup', this.stopDrag);
    },
    toggleMenu(e) {
      // 只有在没有拖动的情况下点击才显示菜单
      if (!this.wasDragging) {
        this.isMenuOpen = !this.isMenuOpen;
      }
      this.wasDragging = false; // 重置拖动标志
    }
  },
  beforeUnmount() {
    // 确保在组件销毁前移除所有事件监听器
    document.removeEventListener('mousemove', this.onDrag);
    document.removeEventListener('mouseup', this.stopDrag);
  }
};
</script>

<style scoped>
.draggable-container {
  position: relative;
}

.draggable-box {
  width: 50px;
  width: 50px;
  height: 50px;
  background-color: #ffffff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: move;
  position: absolute;
  user-select: none;
}

.menu {
  position: absolute;
  top: 160px;
  left: 0;
  background-color: white;
  border: 1px solid #ccc;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 10px;
  z-index: 1000;
}

.menu ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.menu li {
  padding: 5px 10px;
  cursor: pointer;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style>
